<?php

# Download Counter
# By: David Grega
##################################################################
# Created:		12 Jun 2006
# Last Modified:	12 Jun 2006 by David Grega rootkitted@gmail.com

// Connect to Database

$link = mysql_connect('localhost', 'dgrega_counter', 'counter');
$db_selected = mysql_select_db('dgrega_counter', $link);


// If a file was passed in as a parameter than process the download
// File will only be of format "Filename.ext"
if ($_GET["file"] != "" ) {
	handleDownload($_GET["file"]);
}

// Returns download count for given file
function getCount($file) {
	$file = strtolower($file);

	$query = "SELECT `Count` FROM `downloads` WHERE `File` = '$file' LIMIT 1;";
	$result = mysql_query($query);

	$totalrows = mysql_num_rows($result);

	if ($totalrows > 0) {
		$row = mysql_fetch_assoc($result);

		return $row[Count];
	} else {
		return 0;
	}
}

// After incrementing counter, redirect user to actual file for download
function performRedirect($file) {
	header("Location: http://downloads.terranika.com/" . $file);
	exit;
}

// Handle the download
function handleDownload($file) {
	$file = strtolower($file);

	incrementCount($file);
	performRedirect($file);
}

// Increments counter for given file
function incrementCount($file) {
	$counter = getCount($file);

	if ($counter == 0) {
		$query = "INSERT INTO `downloads` ( `ID` , `File` , `Count` ) VALUES ('', '" . $file . "', '1');";
		mysql_query($query);
	} else {
		$query = "UPDATE `downloads` SET `Count` = '" . ($counter + 1) . "' WHERE `File` = '" . $file . "' LIMIT 1 ;";
		mysql_query($query);
	}
}


?>